<template>
  <div class="tables-browser h-full flex flex-col">
    <div class="tables-browser-header p-3 border-b border-gray-200 bg-gray-50">
      <div class="flex items-center justify-between">
        <h3 class="text-sm font-medium text-gray-800">{{ database }} 中的表</h3>
        <div class="flex items-center space-x-2">
          <el-input
            v-model="searchQuery"
            placeholder="搜索表..."
            size="small"
            clearable
            prefix-icon="Search"
            class="w-48"
          />
          <el-button
            size="small"
            icon="Refresh"
            @click="handleRefresh"
            :loading="loading"
            title="刷新表列表"
          />
          <el-select 
            v-model="displayMode" 
            size="small"
            class="w-32"
          >
            <el-option label="卡片视图" value="cards" />
            <el-option label="列表视图" value="list" />
          </el-select>
        </div>
      </div>
    </div>
    
    <div class="tables-browser-content flex-1 overflow-auto p-4">
      <!-- 加载中 -->
      <div v-if="loading" class="h-full flex items-center justify-center">
        <el-icon class="text-3xl text-blue-500 animate-spin"><Loading /></el-icon>
        <span class="ml-2">加载表数据...</span>
      </div>
      
      <!-- 无数据 -->
      <div v-else-if="filteredTables.length === 0" class="h-full flex flex-col items-center justify-center text-gray-500">
        <el-icon class="text-4xl mb-3"><Box /></el-icon>
        <p v-if="searchQuery">没有找到匹配 "{{ searchQuery }}" 的表</p>
        <p v-else>该数据库没有表</p>
      </div>
      
      <!-- 卡片视图 -->
      <div v-else-if="displayMode === 'cards'" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        <div
          v-for="table in filteredTables"
          :key="table.name"
          class="table-card border border-gray-200 rounded-md shadow-sm hover:shadow-md transition-shadow p-4 cursor-pointer"
          @click="openTable(table)"
          @contextmenu.prevent="showTableContextMenu($event, table)"
        >
          <div class="flex items-start">
            <el-icon class="text-green-600 mr-2 text-lg mt-1"><Grid /></el-icon>
            <div class="flex-1 min-w-0">
              <h4 class="text-sm font-medium text-gray-900 truncate" :title="table.name">
                {{ table.name }}
              </h4>
              <p v-if="table.comment" class="text-xs text-gray-500 mt-1 truncate" :title="table.comment">
                {{ table.comment }}
              </p>
              <p class="text-xs text-gray-500 mt-1">
                {{ table.rowCount ?? '?' }} 行
              </p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 列表视图 -->
      <div v-else class="border border-gray-200 rounded-md overflow-hidden">
        <el-table 
          :data="filteredTables" 
          stripe 
          border
          @row-contextmenu="handleRowContextMenu"
        >
          <el-table-column label="表名" prop="name" min-width="180" />
          <el-table-column label="注释" prop="comment" min-width="220" />
          <el-table-column label="记录数" prop="rowCount" width="100" align="right" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useTabStore, useMenuStore } from '@/stores'
import { DatabaseService } from '@/services/database'
import { ElMessage } from 'element-plus'
import { Box, Loading, Grid } from '@element-plus/icons-vue'

const props = defineProps({
  connectionId: {
    type: String,
    required: true
  },
  database: {
    type: String,
    required: true
  },
  tables: {
    type: Array,
    default: () => []
  }
})

const tabStore = useTabStore()
const menuStore = useMenuStore() // 使用全局菜单管理器

const loading = ref(true)
const tableData = ref([])
const searchQuery = ref('')
const displayMode = ref('list') // 'cards' 或 'list'

// 过滤后的表
const filteredTables = computed(() => {
  if (!searchQuery.value) return tableData.value
  
  const query = searchQuery.value.toLowerCase()
  return tableData.value.filter(table => 
    table.name.toLowerCase().includes(query) || 
    (table.comment && table.comment.toLowerCase().includes(query))
  )
})

// 加载表数据
const loadTableData = async () => {
  loading.value = true
  
  try {
    // 如果指定了表名列表，只加载这些表
    if (props.tables && props.tables.length > 0) {
      // 首先获取所有表信息，这样可以获取到注释和记录数
      const allTables = await DatabaseService.listTables(
        props.connectionId,
        props.database
      )
      
      // 筛选出需要的表
      const tables = props.tables.map(tableName => {
        // 尝试从所有表中找到匹配的表信息
        const tableInfo = allTables.find(t => t.name === tableName)
        
        if (tableInfo) {
          return {
            name: tableName,
            comment: tableInfo.comment || '',
            rowCount: tableInfo.rowCount || '-'
          }
        } else {
          // 如果没有找到，返回基本信息
          return {
            name: tableName,
            comment: '',
            rowCount: '-'
          }
        }
      })
      
      tableData.value = tables
    } else {
      // 加载所有表
      const allTables = await DatabaseService.listTables(
        props.connectionId,
        props.database
      )
      
      // 转换表数据格式
      tableData.value = allTables
        .filter(t => t.type !== 'VIEW') // 排除视图
        .map(t => ({
          name: t.name,
          comment: t.comment || '',
          rowCount: t.rowCount || '-'
        }))
    }
  } catch (error) {
    ElMessage.error('加载表数据失败: ' + error.message)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 浏览表数据
const openTableData = (tableName) => {
  tabStore.createBrowseTab(
    props.connectionId,
    props.database,
    tableName
  )
}

// 设计表
const openTableDesign = (tableName) => {
  tabStore.createDesignTab(
    props.connectionId,
    props.database,
    tableName
  )
}

// 创建查询
const createQuery = (tableName) => {
  const sql = `SELECT * FROM ${tableName} LIMIT 100;`
  
  tabStore.createQueryTab(
    props.connectionId,
    {
      database: props.database,
      title: `${tableName} - 查询`,
      sql
    }
  )
}

// 刷新表数据
const refreshTableData = async (tableName) => {
  try {
    // 使用标准API刷新表数据
    const allTables = await DatabaseService.listTables(
      props.connectionId,
      props.database
    )
    
    // 找到需要刷新的表
    const tableInfo = allTables.find(t => t.name === tableName)
    if (tableInfo) {
      // 更新表数据
      const tableIndex = tableData.value.findIndex(t => t.name === tableName)
      if (tableIndex !== -1) {
        tableData.value[tableIndex].rowCount = tableInfo.rowCount || '-'
        tableData.value[tableIndex].comment = tableInfo.comment || ''
        ElMessage.success(`表 ${tableName} 数据已刷新`)
      }
    }
  } catch (error) {
    ElMessage.error(`刷新表 ${tableName} 数据失败: ${error.message}`)
  }
}

// 刷新所有表列表
const handleRefresh = async () => {
  try {
    await loadTableData()
    ElMessage.success('表列表已刷新')
  } catch (error) {
    ElMessage.error('刷新表列表失败: ' + error.message)
  }
}

// 打开表（根据当前首选操作）
const openTable = (table) => {
  openTableData(table.name)
}

// 显示表的上下文菜单 - 卡片视图
const showTableContextMenu = (event, table) => {
  // 阻止默认右键菜单
  event.preventDefault()
  event.stopPropagation()
  
  // 准备菜单数据，确保连接ID和表名正确传递
  const tableData = {
    type: 'table',
    name: table.name,
    connection: { id: props.connectionId },
    database: { name: props.database },
    // 添加冗余字段，以防有些组件使用不同的结构
    connectionId: props.connectionId,
    table: table.name
  }
  
  console.log('显示表右键菜单:', {
    x: event.clientX,
    y: event.clientY,
    table: table.name,
    connectionId: props.connectionId
  })
  
  // 显示全局菜单
  menuStore.showMenu({
    type: 'tableBrowser',
    data: tableData,
    x: event.clientX,
    y: event.clientY,
    onCommand: handleMenuCommand
  })
}

// 处理表格行的右键菜单 - 列表视图
const handleRowContextMenu = (row, column, event) => {
  // 阻止默认右键菜单
  event.preventDefault()
  event.stopPropagation()
  
  // 准备菜单数据，确保连接ID和表名正确传递
  const tableData = {
    type: 'table',
    name: row.name,
    connection: { id: props.connectionId },
    database: { name: props.database },
    // 添加冗余字段，以防有些组件使用不同的结构
    connectionId: props.connectionId,
    table: row.name
  }
  
  console.log('显示表格行右键菜单:', {
    x: event.clientX,
    y: event.clientY,
    table: row.name,
    connectionId: props.connectionId
  })
  
  // 显示全局菜单
  menuStore.showMenu({
    type: 'tableBrowser',
    data: tableData,
    x: event.clientX,
    y: event.clientY,
    onCommand: handleMenuCommand
  })
}

// 处理菜单命令
const handleMenuCommand = (command, data) => {
  if (!data) return
  
  switch (command) {
    case 'browseData':
      openTableData(data.name)
      break
    case 'designTable':
      openTableDesign(data.name)
      break
    case 'newQuery':
      createQuery(data.name)
      break
    case 'refresh':
      refreshTableData(data.name)
      break
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadTableData()
})

// 组件卸载时清理菜单状态
onUnmounted(() => {
  // 如果有菜单打开，关闭它
  if (menuStore.isVisible) {
    menuStore.closeMenu()
  }
})
</script>

<style scoped>
.tables-browser {
  background-color: white;
}

.table-card {
  background-color: white;
}

.table-card:hover {
  background-color: #f9fafb;
}
</style> 